package pay.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import pay.enm.QueryTranEnum;
import pay.portal.web.message.CZTXRecord;

public class GetCZTXRecordFromXml {

	public static List<CZTXRecord> getRecords(String xmlStr, String tranCode) {
		List<CZTXRecord> recordList = new ArrayList<CZTXRecord>();
		try {

			Document document = DocumentHelper.parseText(xmlStr);

			// 获取根节点元素对象
			Element node = document.getRootElement();
			Element plainEle = node.element("plain");

			Element resultsEle = plainEle.element("results");

			recordList = getRecords(resultsEle, tranCode);

		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return recordList;

	}

	private static List<CZTXRecord> getRecords(Element resultsEle, String tranCode) {
		List<CZTXRecord> recordList = new ArrayList<CZTXRecord>();
		Iterator<Element> it = resultsEle.elementIterator();
		// 遍历
		while (it.hasNext()) {
			CZTXRecord record = new CZTXRecord();
			// 获取某个子节点对象
			Element result = it.next();
			record.setTypeCode(tranCode);

			String date = result.element("txn_date").getText();
			String time = result.element("txn_time").getText();
			Long cts = getCts(date, time);
			record.setCts(cts);
			record.setCtsStr(DateUtil.longToLongDate(cts));
			record.setMchnt_ssn(result.element("mchnt_ssn").getText());
			record.setTypeStr(QueryTranEnum.getTypeStr(tranCode));
			String tranFlag = QueryTranEnum.getTypeFlag(tranCode);
			record.setTypeFlag(tranFlag);
			String amt = result.element("txn_amt").getText();
			record.setAmt(BalanceUtils.getFYVal(amt));
			recordList.add(record);
		}

		return recordList;
	}

	private static Long getCts(String month, String time) {
		String dateTimeString = month + time;
		return DateUtil.ToDateTimeFrom01(dateTimeString);
	}

}
